<!-- 分类选择，可拖拽 二级三级分类 -->
<template>
  <div class="form-item col-1">
    <div style="display: flex">
      <span>{{ config.title }}</span>
      <a-tooltip v-if="config.tips">
        <template slot="title"> Tips: {{ config.tips }} </template>
        <a-icon type="alert" style="color: #ff9b19; font-size: 18px" />
      </a-tooltip>
    </div>
    <div>
      <div
        style="margin-top: 15px"
        :class="{
          'sortable-body': true,
          'in-drag': inDrag,
          'out-drag': !inDrag,
        }"
      >
        <!-- 拖拽容器 -->
        <draggable
          tag="ul"
          :list="config.value.list"
          v-bind="dragOptions"
          @start="inDrag = true"
        >
          <!-- 动画 -->
          <!--<transition-group type="transition" :name="!inDrag ? 'flip-list' : null">-->

          <!-- item -->
          <li
            v-for="(item, index) in config.value.list"
            :key="item.id"
            :class="{ 'in-hover': inHover == item.id }"
            @mousemove="inHover = item.id"
            @mouseleave="inHover = ''"
          >
            <div class="goods-box">
              <div class="show-img" v-if="item.thumb" @click="openUpload(item.id)">
                <img :src="item.thumb">
                <a-icon class="icon-close11" type="close-circle" @click.stop="deleteImg(item)" title="点击清除图片"/>
              </div>
              <div class="choose-img" v-else @click="openUpload(item.id)">
                <i class="iconfont icon-jiahao"></i>
                <span>点击上传</span>
              </div>
              <span style="flex:1;">分类名称： {{ item.name }}</span>
            </div>

            <div class="id-name">ID： {{ item.id }}</div>

            <div class="buttons">
              <span
                class="ignore-elements"
                @click.stop="handle_component_delete(item,item.id,0,0,1)"
              >
                <i class="iconfont icon-ht_operation_delete" />
              </span>
              <!-- 置顶 -->
              <!-- <span class="ignore-elements" @click.stop="handle_component_top(item.id)">
                   <i class="iconfont icon-top_place" style="font-size: 20px"/>
                 </span> -->
            </div>

            <div
              v-if="item.children && item.children.length > 0"
              style=""
              class="d-flex flex-col"
            >
            <!-- closable -->
              <p style="padding: 6px 0;font-weight: bold;">二级分类</p>
              <div>
                <a-tag
                style="margin-bottom: 8px;"
                v-for="itemTwo in item.children"
                :key="itemTwo.id"
                closable
                @click.stop="clickCateTwo({itemOne:item.id, itemTwo:itemTwo.id,data: itemTwo.children})"
                @close="handle_component_delete(item,item.id,itemTwo.id,0,2)"
                :color="itemCateTwoActive == itemTwo.id ? '#29ba9c' : ''"
                >{{ itemTwo.name }}</a-tag
              >
              </div>
            </div>
            <!-- 没有二级分类时提示添加 -->
            <a-alert v-else message="暂无二级分类 ！请选择其他 ~" type="error" show-icon style="margin-top: 10px;font-weight: bold;"/>

            <div
              v-if="itemCateActive == item.id &&itemThreeCateActive && itemThreeCateActive.length > 0"
              style=""
              class="d-flex flex-col"
            >
              <p style="padding: 6px 0;font-weight: bold;">三级分类</p>
              <div>
                <a-tag
                style="margin-bottom: 8px;"
                v-for="item in itemThreeCateActive"
                :key="item.id"
                closable
                @close="handle_component_delete(item,itemCateActive,itemCateTwoActive,item.id,3)"
                >{{ item.name }}</a-tag
              >
              </div>
              
            </div>
            <!-- <image-upload :ref="`imageUpload`+item.id"
              :value.sync="item.thumb"
              :config="config"
              :rootConfig="rootConfig"
              @confirm="sureImg(item,$event)">
            </image-upload> -->
              <images-upload :ref="`imageUpload`+item.id" :type=1 selNum='one' @sure='(name,uploadShow,fileList) => {sureImg(item,name,uploadShow,fileList)}'>

              </images-upload>               
          </li>
          <li v-if="config.value.list.length <= 0" :key="0">
            <a-empty />
          </li>

          
          <!--</transition-group>-->
        </draggable>

        <!-- 删除所有组件 -->
        <div style="text-align: center; margin-top: 10px">
          <a-button
            type="primary"
            style="width: 310px"
            @click="handle_open_dialog"
          >
            点击添加
          </a-button>
          <!--<span class="button-clear-all" @click="toAdd">添加组件</span>-->
          <!--<span class="button-clear-all" @click="">清除所有组件</span>-->
        </div>
      </div>
    </div>
    <!--{{value}}-->
    <!-- 弹窗 -->
    <goods-manager
      v-if="initUTree"
      ref="goodsManager"
      goods_type="categoryDraggable"
      :config="config"
      :is_from="is_from"
      @onComfirm="update_goods_list"
      :extinfo="{}"
    />
  </div>
</template>

<script>
import draggable from "vuedraggable";
// 商品数据弹窗
import goodsManager from "@/system-components/dialog-goods-manager/index.vue";
import imageUpload from '../../../../system-components/image-upload/index.vue';
import imagesUpload from '../../../../system-components/images-upload/index.vue'
// Main code
export default {
  props: ["value", "config", "rootConfig", "is_from"],

  components: {
    draggable,
    goodsManager,
    imageUpload,
    imagesUpload
  },

  data() {
    return {
      initUTree: true,//处理重新初始化tree组件，不然点击弹窗选择确认后，关闭弹窗后，在列表删除刚刚选择的数据，再次打开后关闭弹窗，后再次把上次选择的选中返回
      itemCateActive: 0,//当前选中的一级分类id
      itemCateTwoActive: 0, //当前选中的二级分类id
      itemThreeCateActive: [],//当前选中的二级分类下级分类数组
      // 拖拽组件参数
      dragOptions: {
        animation: 200, // 动画时间
        group: "description",
        disabled: false,
        ghostClass: "sortable-ghost",
        dragClass: "sortable-drag",
        filter: ".ignore-elements",
      },
      inDrag: false, // 是否正在拖拽
      inHover: 0, // 鼠标 hover 的 <li> 的 component_id
    };
  },

  computed: {
    current_value() {
      console.log('分类组件的初始数据：：',this.value)
      return this.value;
    },
  },

  mounted() {
    this.config.value = this.current_value;
  },
  updated() {
    this.config.value = this.current_value;
  },

  methods: {
    initCateActive(){
      this.itemCateActive = 0;//当前选中的一级分类id
      this.itemCateTwoActive = 0; //当前选中的二级分类id
      this.itemThreeCateActive = [];//当前选中的二级分类下级分类数组
    },
    /**
     * 打开商品数据配置的弹窗
     */
    handle_open_dialog() {
      // if(this.config.value.length > 100) {
      // this.$message.error('最多只能添加100个');
      // return
      // }
      let checkedKeys = this.config.value.checkedKeys;
      let AllParent = this.config.value.list;//当前已选中的数组（包含一级）
      let treeToArray = this.treeToArray(AllParent);//扁平化数组
      let selectedRows = []
      treeToArray.forEach(element => {
        if(checkedKeys.indexOf(element.id) > -1) {
          selectedRows.push(element)
        }
      });
      this.$refs.goodsManager.oldAllSelectedList = this.config.value.list;
      this.$refs.goodsManager.oldAllcheckedKeys = checkedKeys;
      this.initCateActive();
      this.$refs.goodsManager.show(selectedRows);
    },
    treeToArray(tree) {
      // 将tree转为扁平化数组
      var res = []
      for (const item of tree) {
        const { children, ...i } = item
        if (children && children.length) {
          res = res.concat(this.treeToArray(children))
        }
        res.push(i)
      }
      return res
    },
    /**
     * 更新商品列表
     */
    update_goods_list(list, extinfo) {
      try {
        console.log("关闭弹窗后传递的数据：：：：", list, extinfo);
        this.config.value.checkedKeys = [...extinfo.checkedKeys];
        this.config.value.list = [...extinfo.parentAll];
        let current_value = this.config.value;
        this.$emit("input", current_value);
      } catch (error) {
        console.log(error)
      }
      
      
      // this.config.value = [...list];
      // let current_value = this.config.value;
      // this.$emit('input', current_value);
    },
    /**
     * 结束拖拽
     */
    handleDragEnd(c) {
      this.inDrag = false;
    },
    /**
     * 删除组件
     * @param {Number} id 数组索引
     */
    handle_component_delete(list,id,tid,sid,num) {
      this.initUTree = false;
      
      let KeyIndex = 0;
      try {
        for (let i = this.config.value.list.length -1; i >= 0; i--) {
          if (this.config.value.list[i].id == id) {
            if(num == 1){
              this.hadnleDelKeys(list);
              this.config.value.list.splice(i, 1);
            } 

            KeyIndex = this.config.value.checkedKeys.indexOf(id);//获取一级的key位置
            if(KeyIndex > -1) this.config.value.checkedKeys.splice(KeyIndex,1);//需要把一级的key删除，因为现在删除了其中的二级或者三级，一级的key应该删除，否则tree那里会一级分类全选状态

            if(num > 1){
              for (let i2 = this.config.value.list[i].children.length -1; i2 >= 0; i2--) {
                if (this.config.value.list[i].children[i2].id == tid) {
                  if(num == 2){
                    this.hadnleDelKeys(this.config.value.list[i].children[i2]);
                    this.config.value.list[i].children.splice(i2, 1);
                  } 

                  KeyIndex = this.config.value.checkedKeys.indexOf(tid);//获取一级的key位置
                  if(KeyIndex > -1) this.config.value.checkedKeys.splice(KeyIndex,1);//需要把一级的key删除，因为现在删除了其中的二级或者三级，一级的key应该删除，否则tree那里会一级分类全选状态
                  if(this.config.value.list[i].children&&this.config.value.list[i].children.length == 0){
                    // 三级都删除完了，需要把二级删掉
                    this.config.value.list.splice(i, 1);
                  }
                  if(num == 3) {
                    for (let i3 = this.config.value.list[i].children[i2].children.length-1; i3 >= 0; i3--) {
                      if (this.config.value.list[i].children[i2].children[i3].id == sid) {
                        this.config.value.list[i].children[i2].children.splice(i3, 1);
                        if(this.config.value.list[i].children[i2].children&&this.config.value.list[i].children[i2].children.length == 0){
                          // 三级都删除完了，需要把二级删掉
                          this.hadnleDelKeys(this.config.value.list[i].children[i3]);
                          this.config.value.list[i].children.splice(i2, 1);
                        }
                      }
                    }
                  }
                }
              } 
            }
          }
        }
      } catch (error) {
        console.log("handle_component_delete error::::",error)
      }
      let current_value = this.config.value;
      this.$emit("input", current_value);
      setTimeout(() => {
        this.initUTree = true;//处理重新初始化tree组件，不然点击弹窗选择确认后，关闭弹窗后，在列表删除刚刚选择的数据，再次打开后关闭弹窗，后再次把上次选择的选中返回
      }, 250);
    },

    hadnleDelKeys (list) {
      let index = this.config.value.checkedKeys.indexOf(list.id);
      if(index > -1) this.config.value.checkedKeys.splice(index,1);
      if(list.children && list.children) {
        list.children.forEach(childData => this.hadnleDelKeys(childData))
      }
    },

    handle_component_top(id) {
      // 置顶
      for (let i = 0; i < this.config.value.list.length; i++) {
        if (this.config.value.list[i].id == id) {
          let last_one = this.config.value.list.splice(i, 1);
          this.config.value.list.unshift(last_one[0]);
        }
      }
      let current_value = this.config.value;
      this.$emit("input", current_value);
    },
    changeType() {
      let current_value = this.config.value;
      this.$emit("input", current_value);
    },
    handleClose(id) {
      console.log(id);
    },
    clickCateTwo(item) {
      let {itemOne,itemTwo,data=[]} = item;
      this.itemCateActive = itemOne;
      this.itemCateTwoActive = itemTwo;
      this.itemThreeCateActive = data;
    },
    openUpload(id) {
      this.$refs[`imageUpload${id}`][0].show();
    },
			sureImg(item,name,uploadShow,fileList) {
				    item.image = fileList[0].url;
			},
    deleteImg(item) {
      item.thumb = "";
    },
  },
};
</script>

<style lang="less" scoped>
// 拖拽区域
.sortable-body {
  // 删除所有组件
  .button-clear-all {
    display: inline-block;
    width: 88px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    margin-bottom: 12px;
    font-size: 14px;
    font-weight: bold;
    cursor: pointer;
    &:hover {
      background: #29ba9c;
      color: #ffffff;
      border-radius: 12px;
    }
  }

  // 组件列表
  ul {
    list-style: none;
    padding: 0px;
    margin: 0px;

    li {
      cursor: move;
      position: relative;
      padding: 25px 10px;
      margin-bottom: 16px;
      width: 100%;
      /*height: 48px;*/
      /*line-height: 48px;*/
      background: #fff;
      box-sizing: border-box;
      box-shadow: 0px 0px 0px 1px #e9eaec;
      display: flex;
      flex-direction: column;

      // 鼠标滑过
      &.in-hover {
        /*background: #29ba9c;*/
        /*color: #fff;*/
        box-shadow: 0px 2px 6px 0px rgba(188, 195, 206, 0.8);
        .buttons {
          color: #29ba9c;
          display: block;
        }
      }

      // 拖拽中
      &.sortable-ghost,
      &.sortable-chosen {
        /*opacity: .2 !important;*/
        /*background: #29ba9c;*/
        box-shadow: 0px 2px 6px 0px rgba(188, 195, 206, 0.8);
        /*color: #fff;*/
        span {
          color: #29ba9c;
        }
      }

      p {
        margin: 0;
      }

      .id-name {
        position: absolute;
        left: 10px;
        top: 0px;
      }
      .activity-name {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      // 按钮区域
      .buttons {
        display: none;
        position: absolute;
        right: 10px;
        top: 0px;
        text-align: right;

        > span {
          text-align: center;
          vertical-align: middle;
          display: inline-block;
          background: #fff;
          border-radius: 100%;
          width: 24px;
          height: 24px;
          line-height: 24px;
          &:hover {
            cursor: pointer;
          }
        }
      }
    }
  }
}

.flip-list-move {
  transition: transform 0.5s;
}
.no-move {
  transition: transform 0s;
}

.goods-box {
  background-color: #fbfbfb;
  border-radius: 5px;
  padding: 10px;
  width: 100%;
  display: flex;
  .img-box {
    flex: 0 0 80px;
    margin-right: 10px;
    img {
      width: 100%;
    }
  }
  .right {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-self: center;
    justify-self: center;
  }
}

.cateItem {
  padding: 0 10px;
  line-height: 24px;
  color: #fff;
  background: rgba(41, 186, 156, 0.5);
  margin: 0 8px 8px 0;
}

.d-flex {
  display: flex;
  flex-wrap: wrap;
}
.flex-col {
  flex-direction: column;
}
.choose-img {
    margin: 0 12px 0 0;
    width: 65px;
    height: 65px;
    border-radius: 3px;
    border: dashed 1px #e2e2e2;
    display: flex;
    flex-direction: column;
    align-self: center;
    justify-content: center;
    text-align: center;
    color: #5e5e5e;
    cursor: pointer;
    font-size: 12px;
    i {
      height: 28px;
    }
  }

  .choose-img:hover, .show-img:hover {
    color: #29ba9c;
    border-color: #29ba9c;
  }

  .show-img {
    position: relative;
    width: 65px;
    margin: 0 12px 0 0;
    border: dashed 1px #e2e2e2;
    cursor: pointer;
    img {
      width: 100%;
    }
    .icon-close11 {
      position: absolute;
      top: -10px;
      right: -9px;
      color: #999;
      font-size: 18px;
    }
  }
</style>
